package com.liuwei.spring.cloud.common.utils;/**
 * @author : FileDetector
 * @version V1.0
 * @date: 2023/12/25 10:05 AM
 * @Description: TODO
 */

import info.monitorenter.cpdetector.io.*;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author : FileDetector
 * @version V1.0
 * @date: 2023/12/25 10:05 AM
 * @Description: TODO
 */
public class FileDetector {

    public static void main(String[] args) throws IOException {
        File file = new File("/Users/liuwei/workplace/linux.md");
        Charset charset = detect(file);
        System.out.println(charset);
    }

    /**
     * https://blog.csdn.net/henryzhang2009/article/details/79119066
     * @param file
     * @return
     * @throws IOException
     */
    public static Charset detect(File file) throws IOException {
        // 获取 CodepageDetectorProxy 实例
        CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
        // 添加解析器，会使用到添加的后 2 个 ext 里的 jar 包
        detector.add(new ParsingDetector(false));
        detector.add(JChardetFacade.getInstance());
        detector.add(ASCIIDetector.getInstance());
        detector.add(UnicodeDetector.getInstance());
        return detector.detectCodepage(file.toURI().toURL());
    }


    /**
     * 指通过判断较短的长度length来返回结果, 有可能丧失准确率，但可以保证执行效率
     * @param ins
     * @param length 指定的识别长度
     * @return
     * @throws IOException
     */
    public static Charset detect(InputStream ins, int length) throws IOException {
        // 获取 CodepageDetectorProxy 实例
        CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
        // 添加解析器，会使用到添加的后 2 个 ext 里的 jar 包
        detector.add(new ParsingDetector(false));
        detector.add(JChardetFacade.getInstance());
        detector.add(ASCIIDetector.getInstance());
        detector.add(UnicodeDetector.getInstance());
        return detector.detectCodepage(ins,length);
    }
}
